<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;
use app\agent\model\Agentuser;
use app\agent\model\Agentmenu;

use think\Cache;
use think\Request;
use think\Controller;

class Base extends Controller
{

    protected $admin = '';
    protected $menu = null;
    protected $model = '';
    protected $exceptAction = []; // 不需要验证权限的action
    protected $rootline = [];
    protected $access = [];
    protected $indexView = 'list'; //Index View
    protected $addView = 'add'; //Add View
    protected $editView = 'edit'; //Edit View
    protected $defaultWhere = []; //default where
    protected $defaultOrder = '';
    protected $searchFields = []; //normal search
    protected $pageSize = ['10', '20', '30', '50', '100', '200'];
    protected $primaryKey = 'id'; //primaryKey
    protected $view = '';

    // 当前代理商ID
    protected $agentId = '';
    // 当前代理商详情
    protected $agentInfo = '';

	public function _initialize()
    {
    	parent::_initialize();

        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();

        $this->menu = Agentmenu::where('url', $module . '/' . $controller . '/' . $action)->find();

        // 获取当前model
        $this->model = $this->request->controller();
        $this->assign('model', $this->model);

        // check route auth
        $this->authCheck();

        // Get local location
        $this->assign('bcn', $this->getLocation());
        // Get menu (初始化后台菜单)
        $this->assign('sidebar', $this->getMenu());
        // Get tabs
        $this->assign('tabs', $this->getTabs());
        $this->assign('currentUrl', $this->request->url());
    }

    /**
     * Check route auth
     */
    private function authCheck()
    {
        $session_agent = session('AGENT');
        
        if(!empty($session_agent->id)){
            $this->admin = $session_agent;

            if(!$this->checkAccess()){
                $this->error('您没有访问权限！');
            }
            $this->assign('agentUser', $session_agent);
        }else{
            if($this->request->isAjax()){
                $this->error('您没有访问权限！', url('agent/auth/login'));
            }else{
                $this->redirect('agent/auth/login');
            }
        }
    }

    /**
     * 权限检查
     * @return bool
     */
    private function checkAccess() {
        if($this->admin->userType == '0') {
            // 超级管理员
            return true;
        }else{
            $agent = model('Agent')
                ->alias('a')
                ->where(['a.id' => $this->admin->agentId])
                ->join('__AGENTPOLICY__ p', 'a.levelId = p.id')
                ->field('a.*, p.reserveAmount, p.buyingPrice, p.level')
                ->find();

            $this->agentId = $this->admin->agentId;
            $this->agentInfo = $agent;

            if(in_array($this->request->action(), $this->exceptAction)){
                return true;
            }

            // 权限
            $this->admin->roles = '1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,26,27,28,29,30';
        }

        $this->access = explode(',', $this->admin->roles);

        if(!$this->menu){
            $this->error('该页面不存在！');
        }

        // 首页 默认有权限
        if($this->request->controller() == 'Index' && $this->request->action() == 'index'){
            return true;
        }

        if(!in_array($this->menu->id, $this->access)){
            return false;
        }

        return true;
    }

    public function getMenu() {
        //main menu
        $recursive = function ($id, $level) use (&$recursive) {
            $output = '';
            $menus = Agentmenu::where(['parentId' => $id, 'status' => 1])->order('sorting', 'asc')->select();
            foreach ($menus as $menu) {
                // 检查菜单权限
                if (in_array($this->request->action(), $this->exceptAction)) {
                    continue;
                }

                if ($this->admin->userType != '0' && !in_array($menu['id'], $this->access)) {
                    // 超级管理员 不验证权限
                    continue;
                }

                //sub menu
                $submenus = $recursive($menu->id, $level + 1);
                $output .= '<li class="nav-item' . ($this->menu && in_array($menu->id, $this->rootline) ? ' active open' : '') . '">';
                $output .= '<a href="';
                $output .= url($menu->url);
                //target
                if ($menu->target) {
                    $output .= '" target="' . $menu->target . '"';
                }
                $output .= '" class="nav-link' . ($submenus ? ' nav-toggle' : '') . '">';
                //icon
                if ($menu->icon) {
                    $output .= '<i class="' . $menu->icon . '"></i>';
                }
                $output .= '<span class="title">' . $menu->name . '</span>';
                if ($submenus) {
                    $output .= '<span class="arrow"></span>';
                }
                //current
                $module = $this->request->module();
                $controller = $this->request->controller();
                $action = $this->request->action();
                $current = Agentmenu::where(['url' => $module . '/' . $controller . '/' . $action])->find();
                $parentIds = $this->getParentIds($current['parentId']);
                $parentIdsArr = explode(',' , $parentIds);
                if ($this->menu->id == $menu->id || in_array($menu->id, $parentIdsArr)) {
                    $output .= '<span class="selected"></span>';
                }
                $output .= '</a>';
                //sub menu
                $output .= $submenus;
                $output .= '</li>';
            }
            if ($output && $level > 0) {
                $output = '<ul class="sub-menu">' . $output . '</ul>';
            }
            return $output;
        };

        return $recursive(0, 0);
    }

    // 得到父辈、爷辈、祖辈...的集合
    public function getParentIds($parentId, $level = 0) {
        $result = Agentmenu::where(['id' => $parentId])->find();
        $parentIds = $result['id'];

        if($result['parentId']){
            $level = $level + 1;
            $parentIds .= ',' . $this->getParentIds($result['parentId'], $level);
        }
        return $parentIds;
    }

    private function getLocation() {
        //BCN
        $bcn = '';
        if ($this->menu) {
            //set page title with translation
            $trans_title_key = strtolower(str_replace(' ', '_', $this->menu->name));
            if (lang($trans_title_key) == $trans_title_key) {
                $this->assign('title', $this->menu->name);
            } else {
                $this->assign('title', lang( $trans_title_key));
            }

            //set bcn by Closure menu
            $recursive = function ($id, $output) use (&$recursive) {
                $this->rootline[] = $id;
                $menu = Agentmenu::find($id);
                $trans_title_key = strtolower(str_replace(' ', '_', $menu->name));
                $title = $menu->name;
                if (lang($trans_title_key) != $trans_title_key) {
                    $title = lang($trans_title_key);
                }
                $link = '<li>';
                if ($this->menu->id == $id) {
                    $link .= '<i class="fa fa-angle-right"></i>&nbsp;<span>' . $title . '</span>';
                } else {
                    if($menu->parentId){
                        // TODO
                        $menu->route = $menu->url != '#' ? strtolower($menu->url) : 'javascript:void(0);';
                        $target = $menu->target ? 'target="'.$menu->target.'"' : '';
                        $link .= '<a href="'.url($menu->url).'" title="'.$title.'" '.$target.'>'.$title.'</a>';
                    }else{
                        $link .= '<i class="fa fa-angle-right"></i>&nbsp;<span>' . $title . '</span>';
                    }
                }
                $link .= '</li>';

                array_unshift($output, $link);

                if ($menu->parentId) {
                    $output = $recursive($menu->parentId, $output);
                }
                return $output;
            };

            $bcn = $this->view->fetch('public/bcn', ['breadcrumbs' => $recursive($this->menu->id, [])]);
            return $bcn;
        }
    }

    private function getTabs() {
        //tabs
        $tabs = '';
        if ($this->menu) {
            $menus = Agentmenu::where(['parentId' => $this->menu->parentId, 'status' => 1])->order('sorting', 'asc')->order('id', 'asc')->select();
            if ($menus) {
                foreach ($menus as $menu) {
                    //title
                    $trans_title_key = strtolower(str_replace(' ', '_', $menu->name));
                    $title = $menu->name;
                    if (lang($trans_title_key) != $trans_title_key) {
                        $title = lang($trans_title_key);
                    }
                    $tabs .= '<li' . ($this->menu->id == $menu->id ? ' class="active"' : '') . '>';
                    $menu->route = strtolower($menu->url);
                    $tabs .= '<a href="' . url($this->request->path(), $this->request->param('id') ? $this->request->param('id') : '') . '" title="' . $title . '">' . $title . '</a>';
                    $tabs .= '</li>';
                }
            }
            return $tabs;
        }
    }


}